<?php

namespace App\Model\Guild;

/**
 * 公会主播
 */
class GuildHost extends GuildBase
{
    protected $table = 'guild_host_manage';
    protected $fillable = [
        'guild_manage_id', 'host_user_id', 'verf_status', 'status', 'host_profile_id', 'income_coin', 'consume_coin'
    ];

    const STATUS_BIND = 1;
    const STATUS_UNBIND = 0;

    function guildInfo()
    {
        return $this->belongsTo(GuildManage::class, 'guild_manage_id', 'id');
    }

    /**
     * 该主播所属公会ID
     */
    static function getGuildId($hostId = 0)
    {
        $where = [
            'host_user_id' => $hostId,
            'status' => self::STATUS_BIND
        ];
        $data = self::where($where)->first();
        return $data ? $data->guild_manage_id : 0;
    }

    /**
     * 获取主播
     */
    static function getHostIds($guildId = 0)
    {
        $where = [
            ['status', 1],
        ];
        if ($guildId && is_array($guildId)) {
            return self::where($where)->whereIn('guild_manage_id', $guildId)->pluck('created_at', 'host_user_id')->toArray();
        }
        $guildId && $where[] = ['guild_manage_id', $guildId];
        return self::where($where)->pluck('created_at', 'host_user_id')->toArray();
    }

    static function getBindTime($userId = 0, $guildId = 0)
    {
        $where = [
            'guild_manage_id' => $guildId,
            'host_user_id' => $userId
        ];
        $data = self::where($where)->first();
        return $data ? (string)$data->created_at : null;
    }

    /**
     * 绑定公会主播
     */
    static function bindHost($hostId = 0, $guildManageId = 0, $vrf = 0, $hostProfileId = '')
    {
        $where = [
            // 'guild_manage_id' => $guildManageId,
            'host_user_id' => $hostId,
            'status' => self::STATUS_BIND,
        ];
        $data = self::where($where)->first();
        if ($data) return false;
        return self::updateOrCreate($where, [
            'guild_manage_id' => $guildManageId,
            'host_user_id' => $hostId,
            'host_profile_id' => $hostProfileId,
            'verf_status' => $vrf,
            'status' => self::STATUS_BIND,
        ]);
    }

    /**
     * 是否公会主播
     */
    static function checkInGuild($hostId = 0, $type = 'bool', $guildIds = [])
    {
        if (!$hostId) return false;
        $where = [
            'host_user_id' => $hostId,
            'status' => self::STATUS_BIND
        ];
        if ($guildIds && !is_array($guildIds)) $guildIds = [$guildIds];
        if (empty($guildIds)) {
            return $type == 'bool'
                ? self::where($where)->count() > 0
                : self::where($where)->orderBy('id', 'desc')->first();
        } else {
            return $type == 'bool'
                ? self::where($where)->whereIn('guild_manage_id', $guildIds)->count() > 0
                : self::where($where)->whereIn('guild_manage_id', $guildIds)->orderBy('id', 'desc')->first();
        }
    }
}
